<style>
	.el-scrollbar {
		overflow: hidden;
		position: relative;
		/* height: 100%; */
	}
</style>

<template>
	<!-- 第一层  上下排列，上面是选项，下面是图标和数据 -->
	<div style="height: calc(100vh - 60px) ;display: block;">
		<!-- 选项 -->
		<div style="display: flex;justify-content:space-evenly; align-items: center; height: 40px;">
			<div>
				<label style="font-size: 24px; vertical-align:middle;">班&nbsp;&nbsp;级：</label>
				<el-select v-model="classSelectValue" placeholder="Select" size="default" style="width: 200px"
					filterable @change="changeClass">
					<el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</div>

			<div>
				<label style="font-size: 24px; vertical-align:middle;">学&nbsp;&nbsp;生：</label>
				<el-select v-model="stuSelectValue" placeholder="Select" size="default" style="width: 200px" filterable
					@change="selectAnalyse">
					<el-option v-for="item in stuOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</div>
		</div>

		<!-- 分左右，左侧图标，右侧数据 -->
		<div style="display: flex;justifyContent:space-between; height: calc(100vh-100px);">
			<div style="flex: 1;">
				<el-select v-model="typeSelectValue" placeholder="Select" size="small"
					style="width: 100px;margin-left: 30px;" filterable @change="typeChange">
					<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
				<el-scrollbar max-height="calc(100vh - 170px)" style="padding: 20px 10px;;">
					<div :id="`chart${index}`" :name="`chart${index}`" style="width: 400px; height:350px;"
						v-for="index in chartCount"></div>
				</el-scrollbar>
			</div>
			<div style="flex: 2;">
				<el-scrollbar max-height="calc(100vh -170px)"
					style="padding: 10px 10px;width: calc(100vw - 650px);height: calc(100vh -170px);">
					<el-table :data="tableData" border style="width: 100%" height="calc(100vh - 190px)">
						<el-table-column :prop="item" :label="item" v-for="(item,index) in tableTitle" :fixed='index<3'
							:min-width='item.length>3?90:0' />
					</el-table>
				</el-scrollbar>
			</div>
		</div>

	</div>
</template>

<script setup lang="ts">
	import { onMounted, ref } from 'vue'
	import * as echarts from 'echarts';
	import axios from '../utils/http';
	import { ElMessage } from 'element-plus';

	const classSelectValue = ref('')
	const stuSelectValue = ref('')

	const classOptions = ref([])
	const stuOptions = ref([])

	const tableData = ref([])

	const tableTitle = ref([]);

	const chartCount = ref(0); // 控制折线图数量


	// 获取学生列表
	const changeClass = (classNum) => {
		// 删除之前数据
		stuOptions.value = [];
		stuSelectValue.value = '';
		chartCount.value = 0;

		axios.get("/student/list/" + classSelectValue.value).then(r => {
			if (r.code != 500) {
				stuOptions.value.push({ value: null, label: '无' });
				r.data.forEach(item => {
					stuOptions.value.push({ value: item.stuNum, label: item.stuName });
				});
				// 默认不选择学生
				stuSelectValue.value = stuOptions.value[0].value;

				selectAnalyse();
			}
		})
	}

	const typeOptions = [
		{
			label: '总分',
			value: '总分'
		},
		{
			label: '校次',
			value: '校次'
		},
		{
			label: '班次',
			value: '班次'
		}];

	const typeSelectValue = ref('总分')

	// 类型改变
	const typeChange = () => {
		selectAnalyse();
	}

	// 获取分析数据
	const selectAnalyse = () => {
		if (typeSelectValue.value != '总分' && !stuSelectValue.value) {
			ElMessage({ type: 'error', message: '查看校次、班次时，必须选择学生' })
			return;
		}

		// console.log('stuSelectValue.value',stuSelectValue.value) ;
		// 清空图表
		tableData.value = [];
		tableTitle.value = [];
		chartCount.value = 0;

		// 需要三种数据，1.折线图数据(科目、3、4个列表(横坐标，3个纵坐标)), 2.tableData, 3.tableTitle
		axios.post("/score/analyse", { type: typeSelectValue.value, classNum: classSelectValue.value, stuNum: stuSelectValue.value })
			.then(res => {
				if (res.code == 500) {
					ElMessage({ type: 'error', message: res.msg })
					return;
				}

				if (res.data.length == 0) {
					ElMessage({ type: 'warning', message: '数据为空' })
					return;
				}

				// console.log('typeSelectValue.value', typeSelectValue.value)
				switch (typeSelectValue.value) {
					case '总分': {
						// console.log('stuSelectValue.value', stuSelectValue.value)
						if (!stuSelectValue.value || stuSelectValue.value == '') {
							// console.log(analyseScoreNotHasStuNum)
							analyseScoreNotHasStuNum(res.data);
						} else {
							analyseScoreHasStuNum(res.data);
						}
						break;
					}
					case '校次': {
						analyseRankHasStuNum(res.data);
						break;
					}
					case '班次': {
						analyseRankHasStuNum(res.data);
						break;
					}
					default: {
						ElMessage({ type: 'error', message: '类型异常，无法渲染图表' })
						break;
					}
				}

			});
	}

	//解析无学生的总分数据表
	const analyseScoreNotHasStuNum = (data : []) => {
		tableTitle.value = ['考试编号', '考试名称', '考试日期'];
		data.forEach(log => {
			const map = { '考试编号': log.examNum, '考试名称': log.examName, '考试日期': log.examDate };
			log.subjectList.forEach(subject => {
				if (!tableTitle.value.includes(subject.subjectName)) {
					tableTitle.value[tableTitle.value.length] = subject.subjectName;
				}
				map[subject.subjectName] = subject.score;
			});
			tableData.value.push(map);
		});
		if (tableTitle.value.includes('总分')) {
			moveArray(tableTitle.value, '总分');
		}
		// console.log('tableTitle.value', tableTitle.value)
		// console.log('tableData.value', tableData.value)

		// 拼接图表
		// 倒序遍历table中的数据，让数据时按照考试时间排列的
		const chartTitle = [];
		//将每个科目的成绩保存到chartList
		const subjectMap = {};
		for (let j = tableData.value.length - 1; j >= 0; j--) {
			const row = tableData.value[j];

			chartTitle.push(row['考试名称']);
			for (let i = 3; i < tableTitle.value.length; i++) {
				if (tableTitle.value[i] in subjectMap) { //subjectMap 已经有这个科目
					subjectMap[tableTitle.value[i]].push(row[tableTitle.value[i]]);
				} else {
					subjectMap[tableTitle.value[i]] = [row[tableTitle.value[i]]];
				}
			}
		}
		const chartMap = {}; // 图表数据汇总
		chartMap['标题'] = chartTitle;
		chartMap['科目'] = subjectMap;
		chartCount.value = Object.keys(subjectMap).length;

		// console.log('chartCount.value', chartCount.value)
		// console.log('chartList', chartMap)

		// 渲染图表
		setTimeout(() => drawChart('chart1', '总分', chartTitle, { '平均分': subjectMap['总分'] }), 1000)
		let index = 2;
		Object.keys(subjectMap).forEach(subject => {
			if (subject != '总分') {
				setTimeout(() => drawChart('chart' + index++, subject, chartTitle, { '平均分': subjectMap[subject] }, false), 1000);
			}
		});
	}

	//解析有学生的总分数据表
	const analyseScoreHasStuNum = (data : []) => {
		tableTitle.value = ['考试编号', '考试名称', '考试日期'];
		data.forEach(log => {
			const map = { '考试编号': log.examNum, '考试名称': log.examName, '考试日期': log.examDate };
			log.subjectList.forEach(subject => {
				if (!tableTitle.value.includes(subject.subjectName)) {
					tableTitle.value[tableTitle.value.length] = subject.subjectName;
					tableTitle.value[tableTitle.value.length] = subject.subjectName + '班次';
					tableTitle.value[tableTitle.value.length] = subject.subjectName + '校次';
				}
				map[subject.subjectName] = subject.score;
				map[subject.subjectName + '班次'] = subject.classRank;
				map[subject.subjectName + '校次'] = subject.schRank;
			});
			tableData.value.push(map);
		});
		if (tableTitle.value.includes('总分')) {
			moveArray(tableTitle.value, '总分');
		}
		if (tableTitle.value.includes('总分班次')) {
			moveArray(tableTitle.value, '总分班次');
		}
		if (tableTitle.value.includes('总分校次')) {
			moveArray(tableTitle.value, '总分校次');
		}
		// console.log('tableTitle.value', tableTitle.value)
		// console.log('tableData.value', tableData.value)

		// 拼接图表
		// 倒序遍历table中的数据，让数据时按照考试时间排列的
		const chartTitle = [];
		//将每个科目的成绩保存到chartList
		const subjectMap = {};
		for (let j = tableData.value.length - 1; j >= 0; j--) {
			const row = tableData.value[j];

			chartTitle.push(row['考试名称']);
			for (let i = 3; i < tableTitle.value.length; i++) {
				if (tableTitle.value[i].length != 2) {
					continue;
				}
				// console.log('row', row)
				// console.log('tableTitle.value[i] + type', tableTitle.value[i] + type)
				// console.log('row[tableTitle.value[i] + type]', row[tableTitle.value[i] + type])
				if (tableTitle.value[i] in subjectMap) { //subjectMap 已经有这个科目
					subjectMap[tableTitle.value[i]].push(row[tableTitle.value[i]]);
				} else {
					subjectMap[tableTitle.value[i]] = [row[tableTitle.value[i]]];
				}
			}
		}
		const chartMap = {}; // 图表数据汇总

		chartCount.value = Object.keys(subjectMap).length;

		// console.log('chartCount.value', chartCount.value)


		axios.get("/score/analyse/" + classSelectValue.value).then(res => {
			if (res.code != 500) {
				// 渲染图表
				setTimeout(() => drawChart('chart1', '总分', chartTitle,
					{ '得分': subjectMap['总分'], '平均分': getClassAvgScore(res.data, '总分') }, false), 1000)
				let index = 2;
				Object.keys(subjectMap).forEach(subject => {
					if (subject != '总分') {
						// console.log('subjectMap[subject]', subjectMap[subject])
						setTimeout(() => drawChart('chart' + index++, subject, chartTitle,
							{ '得分': subjectMap[subject], '平均分': getClassAvgScore(res.data, subject) }, false), 1000);
					}
				});
			}
		})
	}

	const getClassAvgScore = (data : any[], subjectName : string) => {
		const scores = [];
		data.forEach(subjectListMap => {
			subjectListMap['value'].forEach(subject => {
				if (subject.key == subjectName) {
					scores.push(subject.value);
				}
			});
		})
		// console.log('scores', scores)
		return scores.reverse();
	}
	// 解析班次或校次
	const analyseRankHasStuNum = (data : []) => {
		tableTitle.value = ['考试编号', '考试名称', '考试日期'];
		data.forEach(log => {
			const map = { '考试编号': log.examNum, '考试名称': log.examName, '考试日期': log.examDate };
			log.subjectList.forEach(subject => {
				if (!tableTitle.value.includes(subject.subjectName)) {
					tableTitle.value[tableTitle.value.length] = subject.subjectName;
					tableTitle.value[tableTitle.value.length] = subject.subjectName + '班次';
					tableTitle.value[tableTitle.value.length] = subject.subjectName + '校次';
				}
				map[subject.subjectName] = subject.score;
				map[subject.subjectName + '班次'] = subject.classRank;
				map[subject.subjectName + '校次'] = subject.schRank;
			});
			tableData.value.push(map);
		});
		if (tableTitle.value.includes('总分')) {
			moveArray(tableTitle.value, '总分');
		}
		if (tableTitle.value.includes('总分班次')) {
			moveArray(tableTitle.value, '总分班次');
		}
		if (tableTitle.value.includes('总分校次')) {
			moveArray(tableTitle.value, '总分校次');
		}
		// console.log('tableTitle.value', tableTitle.value)
		// console.log('tableData.value', tableData.value)

		// 拼接图表
		let type : string = typeSelectValue.value;
		// 倒序遍历table中的数据，让数据时按照考试时间排列的
		const chartTitle = [];
		//将每个科目的成绩保存到chartList
		const subjectMap = {};
		for (let j = tableData.value.length - 1; j >= 0; j--) {
			const row = tableData.value[j];

			chartTitle.push(row['考试名称']);
			for (let i = 3; i < tableTitle.value.length; i++) {
				if (tableTitle.value[i].length != 2) {
					continue;
				}
				if (tableTitle.value[i] in subjectMap) { //subjectMap 已经有这个科目
					subjectMap[tableTitle.value[i]].push(row[tableTitle.value[i] + type]);
				} else {
					subjectMap[tableTitle.value[i]] = [row[tableTitle.value[i] + type]];
				}
			}
		}
		const chartMap = {}; // 图表数据汇总
		// chartMap['标题'] = chartTitle;
		// chartMap['科目'] = subjectMap;
		// console.log('chartTitle', chartTitle)
		// console.log('subjectMap', subjectMap)
		// console.log('type', type)

		chartCount.value = Object.keys(subjectMap).length;

		// console.log('chartCount.value', chartCount.value)

		// 渲染图表
		if (typeSelectValue.value == '校次')
			setTimeout(() => drawChart('chart1', '总分', chartTitle, { '校次': subjectMap['总分'] }, true), 1000)
		else
			setTimeout(() => drawChart('chart1', '总分', chartTitle, { '班次': subjectMap['总分'] }, true), 1000)
		let index = 2;
		Object.keys(subjectMap).forEach(subject => {
			if (subject != '总分') {
				if (typeSelectValue.value == '校次')
					setTimeout(() => drawChart('chart' + index++, subject, chartTitle, { '校次': subjectMap[subject] }, true), 1000);
				else
					setTimeout(() => drawChart('chart' + index++, subject, chartTitle, { '班次': subjectMap[subject] }, true), 1000);
			}
		});
	}


	const drawChart = (eleId : string, title : String, xData : any[], yData : {}, scale : boolean) => {
		// console.log('eleId', eleId)
		var myChart = echarts.init(document.getElementById(eleId))

		const seriesList = [];
		for (const [key, value] of Object.entries(yData)) {
			seriesList.push({
				name: key,
				data: value,
				type: 'line',
				smooth: true
			});
		}
		// console.log('seriesList', seriesList)

		// 绘制图表
		myChart.setOption({
			title: {
				text: title
			},
			toolbox: {
				show: true,
				feature: {
					magicType: { show: true, type: ['stack', 'tiled'] },
				}
			},
			tooltip: {
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: xData
			},
			yAxis: {
				type: 'value',
				inverse: scale
			},
			legend: {
				data: ['平均分', '中位数', '得分', '校次', '班次']
			},
			series: seriesList
		});
	}

	const moveArray = (arr : any[], source) => {
		// splice 将目标元素替换并将原结果扔回来赋值给它
		let index = arr.indexOf(source)
		if (index != -1) {
			arr.splice(index, 1)
		}
		arr.push(source)
	}


	onMounted(() => {
		axios.get("/classc/list").then(r => {
			if (r.code != 500) {
				// console.log(r)
				r.data.forEach(item => {
					classOptions.value.push({ value: item.classNum, label: item.className });
				});
				classSelectValue.value = classOptions.value[0].value;
				changeClass(classSelectValue.value);
			}
		})
	})
</script>